<script setup lang="ts">
import type { EnvVariableConfig } from "@/modules/dev-env/store/types.ts";
import { computed, ref, watch } from "vue";
import { hc } from "@/framework/vue/util/render.ts";
import { CopyOutlined } from "@ant-design/icons-vue";
import EnvVarSetOperation from "@/modules/dev-env/components/env-var-set-operation.vue";
import { useMitt } from "@/framework/util/events.ts";
import { SettingsEvents } from "@/store/setting-store.ts";
import { copyText } from "@/util/clipboard.ts";

const { config } = defineProps<{
  config: EnvVariableConfig;
}>();

const systemValue = computed(() => native.process.env[config.name]);
const variableValue = ref<string>();

const setVariableValueByConfig = async () => {
  if (config.getValue) {
    variableValue.value = await config.getValue();
  } else {
    variableValue.value = undefined;
  }
};

watch(() => config, setVariableValueByConfig, { immediate: true });

// 监听系统设置变化
useMitt(SettingsEvents, "dev-install-path-changed", () => setVariableValueByConfig());
</script>

<template>
  <a-form-item :label="config.name" :help="config.help">
    <div class="flex aic col-gap-10">
      <a-auto-complete v-if="config.options" :options="config.options" v-model:value="variableValue" class="flex-1" />
      <a-input v-else v-model:value="variableValue" :readonly="config.readonly" class="flex-1" />

      <env-var-set-operation v-if="config.settable" :name="config.name" :value="variableValue" />
      <a-button v-if="config.copyName !== false" :icon="hc(CopyOutlined)" @click="copyText(config.name)">变量名</a-button>
      <a-button :icon="hc(CopyOutlined)" :disabled="!variableValue" @click="copyText(variableValue!)">变量值</a-button>
    </div>
    <template #extra v-if="config.showCurrent">
      <span>当前值：{{ systemValue }}</span>
    </template>
  </a-form-item>
</template>

<style scoped lang="less"></style>
